<?php

namespace App\Http\Controllers;

use App\Http\Models\Post;
use App\Http\Models\PostTopic;
use App\Http\Models\Topic;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class TopicController extends Controller
{
    public function show(Topic $topic)
    {
        // 带文章数的专题详情
        $topic = Topic::query()->withCount(['postTopics'])->find($topic->id);

        // 某个专题的文章详情列表,前10条  [skip->take => offset->limit]
        $posts = $topic->posts()->latest()->take(10)->get();

        // 属于我的文章,但是未投稿
        $my_posts = Post::query()->with('user')->authorBy(Auth::id())->notTopic($topic->id)->latest()->take(10)->get();

        /**
         * 报错备注:
         * Illuminate\Database\Query\Builder:1229 -> compact去掉operator
         */

        return view('topic/show', compact('topic', 'posts', 'my_posts'));
    }

    public function submit(Topic $topic, Request $request)
    {
        // 验证
        $rules = [
            'post_ids' => 'required|array',
        ];
        $this->validate($request, $rules);

        // 保存
        $post_ids = $request->input('post_ids');
        $topic_id = $topic->id;
        foreach ($post_ids as $post_id) {
            PostTopic::query()->firstOrCreate(compact('post_id', 'topic_id'));
        }

        // 渲染
        return back();
    }
}
